<template>
	<section >
		<!--工具条-->
		<el-col :span="24" class="toolbar"  style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model.trim="filters.keyword" placeholder="门店名称或地址"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="getShops">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="shops" :height="520" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" label="序号" width="70">
			</el-table-column>
			<el-table-column prop="name" label="门店名称" width="180" sortable>
			</el-table-column>
			<el-table-column prop="tel" label="联系电话" width="180" sortable>
			</el-table-column>
			<el-table-column prop="registerTime" label="开店日期" width="180" sortable>
			</el-table-column>
			<el-table-column prop="address" label="门店地址" width="180" sortable>
			</el-table-column>
			<el-table-column prop="logo" label="门店logo" width="180" sortable>
                <template scope="scope">
					<el-avatar :size="60" src="https://empty" @error="errorHandler">
						<img width="100px"  :src="scope.row.logo" alt="">
					</el-avatar>
                </template>
			</el-table-column>
			<el-table-column prop="state" label="状态" width="180"  sortable>
				<template scope="scope">
					<span v-if="scope.row.state == 0" style="color:green;">营业存续</span>
					<span v-else-if="scope.row.state == -1" style="color:red;">停业整顿</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" width="170">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--分页工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="total, sizes, prev, pager, next, jumper" @current-change="handleCurrentChange" @size-change="handleSizeChange"
						   :total="total"
						   :current-page="page"
						   :page-size="pageSize"
						   :page-sizes="[5, 10, 20, 50]"
						   style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog title="新增或编辑" :visible.sync="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="门店名称" prop="name">
					<el-input v-model="editForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="门店电话" prop="tel">
					<el-input v-model="editForm.tel" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="门店地址" prop="address">
					<div class="demo-input-suffix" style="display: flex;justify-content: flex-start">
						<el-cascader
								:options="options"
								v-model="selectedOptions"
								@change="handleChange">
						</el-cascader>
						<el-input
								placeholder="请输入详细地址"
								style="width: 70%"
								v-model="afterAddress"
								@blur="detailAddressChange">
						</el-input>
					</div>
				</el-form-item>
				<el-form-item label="开店日期" prop="registerTime">
					<el-date-picker
							v-model="editForm.registerTime"
							type="date"
							placeholder="选择日期">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="门店logo" prop="logo">
					<div class="upload">
						<el-upload
								class="avatar-uploader"
								:action= domain
								:http-request = upqiniu
								:show-file-list="false"
								:before-upload="beforeUpload">
							<img v-if="editForm.logo" :src="editForm.logo" height="150" class="avatar">
							<i v-else class="el-icon-plus avatar-uploader-icon"></i>
						</el-upload>
					</div>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="editForm.state">
						<el-radio class="radio" :label="0">营业存续</el-radio>
						<el-radio class="radio" :label="-1">停业整顿</el-radio>
					</el-radio-group>
				</el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>
    import { regionData, CodeToText } from 'element-china-area-data/src/app'
    import {validatePhoneTwo} from '../../common/js/validate'
    import util from '../../common/js/util'
    import {TextToCode} from "element-china-area-data";
	export default {
		data() {
			return {
				filters: {
                    keyword: ''
				},
                imageUrl: '',
                token: {},
                // 七牛云的上传地址，根据自己所在地区选择，我这里是华南区
                domain: 'https://upload-z2.qiniup.com',
                // 这是七牛云空间的外链默认域名
                qiniuaddr: 'cdn.lvkun.top',
				value:true,
				shops: [],
				employees:[],
				shopTree:[],
				total: 0,
				page: 1,
				pageSize:10,
				listLoading: false,
				sels: [],//列表选中列
				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
                options: regionData,
                selectedOptions: [],
                // 前面部分的地址
                frontAddress: '',
                // 后面的细节地址
                afterAddress: '',
				editFormRules: {
					name: [
						{ required: true, message: '请输入门店名称', trigger: 'blur' }
					],
                    tel: [
                        { required: true, message: '请输入联系方式', trigger: 'blur' },
                        {validator:validatePhoneTwo,trigger: 'blur'}
                    ],
                    address: [
                        { required: true, message: '请输入门店地址', trigger: 'blur' }
                    ]
				},
				//编辑界面数据
				editForm: {
					id: null,
                    name: '',
                    tel:'',
                    registerTime:'',
                    state: 0,
                    address: '',
                    logo: ''
				},
			}
		},
		methods: {
            // 上传文件到七牛云
            upqiniu (req) {
                const config = {
                    headers: {'Content-Type': 'multipart/form-data'}
                }
                let filetype = ''
                if (req.file.type === 'image/png') {
                    filetype = 'png'
                } else {
                    filetype = 'jpg'
                }
                // 重命名要上传的文件
                const keyname = 'lvkun' + new Date() + Math.floor(Math.random() * 100) + '.' + filetype
                // 从后端获取上传凭证token
                this.$http.get('/QiniuUpToken').then(res => {
                    console.log(res)
                    const formdata = new FormData()
                    formdata.append('file', req.file)
                    formdata.append('token', res.data.token)
                    formdata.append('key', res.data.imageUrl)
                    // 获取到凭证之后再将文件上传到七牛云空间
                    this.$http.post(this.domain, formdata, config).then(res => {
                        this.editForm.logo = 'http://' + this.qiniuaddr + '/' + res.data.key;
                    })
                })
            },
            // 验证文件合法性
            beforeUpload (file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
                const isLt2M = file.size / 1024 / 1024 < 2
                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!')
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!')
                }
                return isJPG && isLt2M
            },
			//性别显示转换
			formatSex: function (row, column) {
				return row.state == 0 ? '正常' : row.state == -1 ? '禁用' : '未知';
			},
            //切换当前显示多少条数据
            handleSizeChange(val) {
                this.pageSize = val;
                this.getShops();
            },
            //切换当前页码
			handleCurrentChange(val) {
				this.page = val;
				this.getShops();
			},
            handleChange(arr) {
                let newAddress = '';
                for(var i=0; i<arr.length; i++){
                    newAddress = newAddress + CodeToText[arr[i]]
                }
                this.frontAddress = newAddress;
                this.editForm.address = this.frontAddress + this.afterAddress;
            },
            errorHandler() {
                return true
            },
            detailAddressChange() {
                this.editForm.address = this.frontAddress + this.afterAddress;
            },
            //获取门店列表
			getShops() {
				let para = {
					currentPage: this.page,
					keyword: this.filters.keyword,
					pageSize:this.pageSize
				};
				this.listLoading = true;
				this.$http.post("/shop",para)
					.then(result=>{
                        this.listLoading = false;
                        result = result.data;//直接抽取了一层
                        if(result){//true
                            this.total = result.totals;
                            this.shops = result.rows;
						}else{//false
                            this.$message({
                                message: '查询数据失败！'+result.message,
                                type: 'error'
                            });
						}
					})
					.catch(result=>{
						alert("系统错误！！！")
                    })
			},
            /*查询所有的员工信息*/
            getEmployees(){
			    this.$http.get("/employee")
					.then(result=>{
					    if (result){
                            this.employees = result.data;
						}
					})
					.catch(result=>{

					})
			},
			//删除员工信息
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					let url ="/shop/"+row.id;
					this.$http.delete(url,{})
						.then(result=>{
                            this.listLoading = false;
                            result = result.data;//直接抽取了一层
                            if(result.success){//true
								this.page = 1;
                                this.$message({
                                    message: result.message,
                                    type: 'success'
                                });
                            }else{//false
                                this.$message({
                                    message: result.message,
                                    type: 'error'
                                });
                            }
                            this.getShops();
						})
						.catch(result=>{

						})
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.editFormVisible = true;
                //this.$refs['editForm'].resetFields();//重置表单内容和表单验证

                this.editForm = Object.assign({}, row);
                //1.回显详细地址
                var reg = /.+?(省|市|自治区|自治州|县|区|區)/g;
				// this.editForm.address 父组件传递的地址信息
                var arr = this.editForm.address.match(reg);

                // 截取剩余的字符串 放在详细地址input框中
                var frontAddress = this.editForm.address.indexOf(arr[arr.length-1]);
                frontAddress = frontAddress + arr[arr.length-1].length;
                this.afterAddress = this.editForm.address.substring(frontAddress,this.editForm.address.length);
				//2.回显省市区三级地址
                var placeInfo = [];
                var province = TextToCode[arr[0]];
                placeInfo[0] = province.code
                if(arr.length > 1) {
                    var city = province[arr[1]];
                    placeInfo[1] = city.code
                }
                if(arr.length > 2){
                    if(city[arr[2]]){
                        var region = city[arr[2]];
                        placeInfo[2] = region.code
                    }
                }
                this.selectedOptions = placeInfo;

                this.$refs['editForm'].clearValidate();//重置表单验证
            },
			//显示新增界面
			handleAdd: function () {
				this.editFormVisible = true;
				this.editForm = {
                    id: null,
                    name: '',
                    tel:'',
                    registerTime:'',
                    state: 0,
                    address: '',
                    logo: ''
				};
				this.selectedOptions=[];
				this.afterAddress = '';
                this.getDeptTree();
			},
			//新增或编辑提交
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							let para = Object.assign({}, this.editForm);
                            para.registerTime = (!para.registerTime || para.registerTime == '') ? '' : util.formatDate.format(new Date(para.registerTime), 'yyyy-MM-dd');
							console.log(para.registerTime)
                            this.$http.put("/shop",para)
								.then(result=>{
								    result = result.data;
								    if(result.success){
                                        this.$message({
                                            message: result.message,
                                            type: 'success'
                                        });
									}else {
                                        this.$message({
                                            message: result.message,
                                            type: 'error'
                                        });
									}
									this.page = 1;
                                    this.editLoading = false;
                                    this.getShops();//刷新页面
                                    this.editFormVisible = false;
                                    this.$refs['editForm'].resetFields();//重置表单验证

								})
								.catch(result=>{
                                    this.editFormVisible = false;
									alert("系统错误")
								})
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					this.$http.patch("/shop",ids)
						.then(result=>{
                            result =result.data;
                            if(result.success){
                                this.$message({
                                    message: result.message,
                                    type: 'success'
                                });
							}else {
                                this.$message({
                                    message: result.message,
                                    type: 'error'
                                });
							}
                            this.listLoading = false;
                            this.page = 1;
                            this.getShops();

						})
						.catch(result=>{
                            this.$message({
                                message: '系统异常',
                                type: 'error'
                            });
						})
				}).catch(() => {

				});
			}
			},
		mounted() {
			this.getShops();
            //this.getEmployees();
		},
		watch:{
		    "filters.keyword"(oldVal,newVal){
				this.oldValue = newVal;
				this.getShops();
			}
		}
	}

</script>

<style scoped>


</style>